import { createStore } from "vuex";

const setLocalCartList = (state) => {
  const { cartList } = state;
  const cartListString = JSON.stringify(cartList);

  localStorage.cartList = cartListString;
};


const getLoalCartList = () => {
  if(localStorage.cartList){
    return JSON.parse(localStorage.cartList)
  }else{
    return {}
  }
}

export default createStore({
  state: {
    cartList: getLoalCartList()
  },
  mutations: {
    addItemToCart(state, payload) {
      const { shopId, productId, product, number } = payload;
      let shopInfo = state.cartList[shopId] || {
        shopName: "",
        productList: {},
      };

      let productInfo = shopInfo.productList[productId];
      if (!productInfo) {
        productInfo = product;
        productInfo.count = 0;
      }

      productInfo.count += number;
      if (productInfo.count < 0) {
        productInfo.count = 0;
      }

      if (productInfo.count > 0) {
        productInfo.check = true;
      }

      shopInfo.productList[productId] = productInfo;

      state.cartList[shopId] = shopInfo;

      setLocalCartList(state)
    },

    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.check = !product.check;
      setLocalCartList(state)
    },

    cleanCartProducts(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCartList(state)
    },

    setCartItemsChecked(state, payload) {
      const { shopId } = payload;
      const products = state.cartList[shopId].productList;
      if (products) {
        for (let key in products) {
          const product = products[key];
          product.check = true;
        }
      }
      setLocalCartList(state)
    },

    changeShopName(state, payload) {
      const { shopId, shopName } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: "",
        productList: {},
      };

      shopInfo.shopName = shopName;
      state.cartList[shopId] = shopInfo;

      setLocalCartList(state)
    },

    clearCartData(state, shopId) {
      state.cartList[shopId].productList = {}
    }

  },
  actions: {},
  modules: {},
});
